import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Context } from '@midwayjs/koa';
import { CacheManager } from '@midwayjs/cache';
import { UserEntity } from '../entity/user';
import { NewzfApiService } from './newzf/api';
import { WXService } from './wx';

/**
 * 课表
 */
@Provide()
export class CourseService extends BaseService {
    @InjectEntityModel(UserEntity)
    userEntity: Repository<UserEntity>;

    @Config('module.app')
    config;

    @Inject()
    ctx: Context;

    @Inject()
    cacheManager: CacheManager;

    @Inject()
    nwezfapi: NewzfApiService;

    @Inject()
    wxService: WXService;


    /**
     * 获取课表
     * @param url 学校地址
     * @param sysType 系统类型
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param year 年份
     * @param term 学期
     * @param refresh 是否刷新
     */
    async get_course(url, sysType, loginType, username, password, year, term, refresh?) {
        const refreshTime = new Date().getHours() >= 0 && new Date().getHours() < 7 ? false : true;
        if (!refreshTime) {
            const course: any = await this.cacheManager.get(`course:${this.ctx.user.userId}`);
            if (!course) {
                return {
                    success: false,
                    message: '系统维护中，请7点后再试',
                    data: null
                }
            }
            return {
                success: true,
                message: '课表查询成功',
                data: course
            }
        }
        if (refresh) {
            const { success, message, data } = await this.update_course(url, sysType, loginType, username, password, year, term);
            if (!success) return { success, message, data };
            return {
                success,
                message,
                data
            }
        }
        const course: any = await this.cacheManager.get(`course:${this.ctx.user.userId}`);
        if (!course) {
            const { success, message, data } = await this.update_course(url, sysType, loginType, username, password, year, term);
            if (!success) return { success, message, data };
            return {
                success,
                message,
                data
            }
        }
        if (new Date().getTime() - course.creatime > 1000 * 60 * 60 * 24) {
            const { success, message, data } = await this.update_course(url, sysType, loginType, username, password, year, term);
            if (!success) return { success, message, data };
            return {
                success,
                message,
                data
            }
        }
        return {
            success: true,
            message: '课表查询成功',
            data: course
        }
    }

    /**
     * 更新课表
     * @param url 学校地址
     * @param sysType 系统类型
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param year 年份
     * @param term 学期
     */
    async update_course(url, sysType, loginType, username, password, year, term) {
        switch (sysType) {
            case 0:
                const { success, message, data } = await this.nwezfapi.get_course(url, loginType, username, password, year, term);
                if (!success) return { success, message, data };
                let course: any = await this.cacheManager.get(`course:${this.ctx.user.userId}`);
                const result = {
                    ...data,
                    startDate: course? course.startDate : this.config.startDate,
                    creatime: new Date().getTime()
                };
                await this.cacheManager.set(`course:${this.ctx.user.userId}`, result, { ttl: null });
                return { success, message, data: result };
            case 1:
                return { success: false, message: '暂不支持', data: null };
        }
    }

    /**
     * 更新日期
     * @param date 日期
     */
    async update_date(date) {
        let course: any = await this.cacheManager.get(`course:${this.ctx.user.userId}`);
        course.startDate = date;
        await this.cacheManager.set(`course:${this.ctx.user.userId}`, course, { ttl: null });
        return {
            success: true,
            message: '更新成功',
            data: null
        }
    }

    /**
     * 课表提醒
     * @param remind 提醒
     */
    async course_remind(remind) {
        if (remind) {
            const { name, username, nickname, openid } = await this.userEntity.findOneBy({ id: this.ctx.user.userId });
            const template_id = "Hty_TGxP-WVm5iT7eIgeNx57D-cv7cNf234AbJ31saM";
            const page = "/pages/index/index";
            const data = {
                "first": {
                    "value": `您已开通上课提醒功能`,
                    "color": "#173177"
                },
                "keyword1": {
                    "value": `${username}`,
                    "color": "#173177"
                },
                "keyword2": {
                    "value": `${name}`,
                    "color": "#173177"
                },
                "keyword3": {
                    "value": `${nickname}`,
                    "color": "#173177"
                },
                "remark": {
                    "value": `如需退订该提醒，请往小程序里关闭即可`,
                    "color": "#f80202"
                }
            }
            const send = await this.wxService.sendTemplateMessage(openid, template_id, page, data);
            if (!send) {
                return {
                    success: false,
                    message: '开启失败',
                    data: null
                }
            }
            const { affected } = await this.userEntity.update({ id: this.ctx.user.userId }, { remind: 1 });
            if (!affected) {
                return {
                    success: false,
                    message: '操作失败',
                }
            }
            return {
                success: true,
                message: '开启成功',
                data: null
            }
        }
        const { affected } = await this.userEntity.update({ id: this.ctx.user.userId }, { remind: 0 });
        if (!affected) {
            return {
                success: false,
                message: '操作失败',
            }
        }
        return {
            success: true,
            message: '关闭成功',
            data: null
        }
    }
}